package com.liuh.fram.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.liuh.fram.err.LocalException;
import com.liuh.fram.err.LocalException.ErrorType;

/**
 * @note gzip解压缩
 * @author liuh
 * */
public class GzipTools extends CompressTools {

	public static final int BUFFER = 1024;

	/**
	 * @note gzip压缩
	 * @author liuh
	 * */
	@Override
	public byte[] compress(byte[] data) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] output = null;
		// 压缩
		try {
			compress(bais, baos);
			output = baos.toByteArray();
		}catch (Exception e) {
			throw new LocalException(ErrorType.parseErr);
		} finally {
			try {
				baos.flush();
				baos.close();
				bais.close();
			} catch (IOException e) {
				throw e;
			}
		}
		return output;
	}

	/**
	 * @note gzip解压
	 * @author liuh
	 * */
	@Override
	public byte[] decompress(byte[] data) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] output = null;
		// 解压缩
		try {
			decompress(bais, baos);
			output = baos.toByteArray();
		} catch (Exception e) {
			throw new LocalException(ErrorType.parseErr);
		} finally {
			try {
				baos.flush();
				baos.close();
				bais.close();
			} catch (IOException e) {
				throw e;
			}

		}
		return output;
	}

	/**
	 * 数据压缩
	 * 
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public void compress(InputStream is, OutputStream os) throws Exception {
		GZIPOutputStream gos = new GZIPOutputStream(os);
		int count;
		byte data[] = new byte[BUFFER];
		while ((count = is.read(data, 0, BUFFER)) != -1) {
			gos.write(data, 0, count);
		}
		gos.finish();
		gos.flush();
		gos.close();
	}

	/**
	 * 数据解压缩
	 * 
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void decompress(InputStream is, OutputStream os)
			throws Exception {
		GZIPInputStream gis = new GZIPInputStream(is);
		int count;
		byte data[] = new byte[BUFFER];
		while ((count = gis.read(data, 0, BUFFER)) != -1) {
			os.write(data, 0, count);
		}
		gis.close();
	}

}